package com.zhiyuancode.mqack.worker;

import com.zhiyuancode.mqack.message.base.MqTypeEnum;
import com.zhiyuancode.mqack.message.base.addressAndMessage.AddressAndMessage4Object;
import com.zhiyuancode.mqack.message.base.addressAndMessage.AddressAndMessage4String;
import org.apache.activemq.command.ActiveMQDestination;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;

/**
 * @author 杨志远
 * email faryangsh@163.com
 * Date    2018-05-03
 */
@Component
public class Sender implements ApplicationContextAware {
    private static JmsMessagingTemplate jmsMessagingTemplate;


//    public static void sendMessage(String mqAddress, String mqContent) {
//        // TODO: 2018/5/3 日志+熔断
//        jmsMessagingTemplate.convertAndSend(mqAddress, mqContent);
//    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        try {
            jmsMessagingTemplate = applicationContext.getBean(JmsMessagingTemplate.class);
        } catch (Exception e) {
            throw new ExceptionInInitializerError("JmsMessagingTemplate autowire failed,maybe it not correctly configure");
        }
    }


    public static void sendMessage(AddressAndMessage4String mqAddressAndMessage) {
        // TODO: 2018/5/3 日志+熔断
        ActiveMQDestination activeMQDestination = MqTypeEnum.generateMqDestination(mqAddressAndMessage.getMqAddress(),
                mqAddressAndMessage.getMqType());
        jmsMessagingTemplate.convertAndSend(activeMQDestination, mqAddressAndMessage.getMessage());
    }

    public static void sendMessage(AddressAndMessage4Object mqAddressAndMessage) {
        // TODO: 2018/5/3 日志+熔断
        ActiveMQDestination activeMQDestination = MqTypeEnum.generateMqDestination(mqAddressAndMessage.getMqAddress(),
                mqAddressAndMessage.getMqType());
        jmsMessagingTemplate.convertAndSend(activeMQDestination, mqAddressAndMessage.getMessage());
    }
}
